// import { login, logout, getInfo } from '@/api/user'
import Vue from 'vue'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    email: '',
    menuItem: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_MENUITEM: (state, menuItem) => {
    state.menuItem = menuItem
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return true
    // return Vue.api.login({ username: username.trim(), password: password }).then(response => {
    //   const { data } = response
    //   commit('SET_TOKEN', data.token)
    //   setToken(data.token)
    //   return data
    // })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      Vue.api.getUserInfo().then(response => {
        const { data } = response
        if (!data) {
          return Promise.reject('Verification failed, please Login again.')
        }
        commit('SET_USERINFO', data)
        commit('SET_EMAIL', data.email)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return Vue.api.logout().then(res => {
      removeToken()
      resetRouter()
      commit('RESET_STATE')
      return res
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  // get menu
  getMenu({ commit }) {
    return Vue.api.getMainMenu().then(res => {
      commit('SET_MENUITEM', res.data)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

